/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-04-24 16:42:22
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-04-26 15:48:53
 * @FilePath: /linux/tcpcalculator/sock.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <strings.h>
#include <arpa/inet.h>
#include <memory>
#include <unistd.h>
#include <vector>
#include <functional>
#include <unordered_map>
#include <sys/types.h>
#include <sys/wait.h>
#include<signal.h>
using namespace std;
static int backlog = 10;
class sock
{
    public:
    sock()
    {}
    ~sock()
    {}
    void Init()
    {
        sockfd_ = socket(AF_INET,SOCK_STREAM,0);
        if(sockfd_<0)
            exit(1);
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local)); 
        socklen_t len = sizeof(local);
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;
        if(bind(sockfd_,(struct sockaddr*)&local,len)>0);    
        cout<<"bind success"<<endl;
    }
    void Listen()
    {
        if(listen(sockfd_,backlog)<0)
        {
            return ;
        }
    }
    int  Accept(std::string &clientip,uint16_t &clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        cout << len << endl;
        int sockfd = accept(sockfd_,(sockaddr*)&client,&len); 
        cout << sockfd << endl;
        if(sockfd<0)   
            return -1;      
        char buffer[64];
        inet_ntop(AF_INET,&client.sin_addr,buffer,sizeof(buffer));
        clientip = buffer;
        clientport = ntohs(client.sin_port);
        return sockfd;
    }
    bool Connect(std::string serverip,uint16_t serverport)
    {
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_port = htons(serverport);
        char buffer[128];
        inet_pton(AF_INET,serverip.c_str(),&(server.sin_addr));
        server.sin_family = AF_INET;
        socklen_t len = sizeof(server);
        int n = connect(sockfd_,(sockaddr*)&server,len);
        if(n<0)
        {
            cout<<"connect error"<<endl;
        return false;

        }
        return true;
    }
    void Close()
    {
        close(sockfd_);
    }
    public:
    int sockfd_;
};